package utils;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

public class DaoUtil<T> {
	public static <T extends Object> T queryBean(String sql,Class<T> clazz,Object... args){
		BeanHandler rsh = new BeanHandler(clazz);
		T result = null;
		try {
			QueryRunner qryRun = new QueryRunner(DBHelper.getDataSource());
			result = (T) qryRun.query(sql, rsh, args);
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return result;
	}
	
	public static <T extends Object> List<T> queryBeanList(String sql,Class<T> clazz,Object...args){
		BeanListHandler<T> rsh = new BeanListHandler<T>(clazz);
		List<T> result = null;
		try{
			QueryRunner qryRun = new QueryRunner(DBHelper.getDataSource());
			result = qryRun.query(sql, rsh,args);
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		return result;
	}
	
	public static Map<String,Object> queryMap(String sql,Object... args){
		MapHandler rsh = new MapHandler();
		Map<String,Object> result = null;
		try{
			QueryRunner qryRun = new QueryRunner(DBHelper.getDataSource());
			result = qryRun.query(sql,rsh,args);
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		return result;
	}
	
	
	public static List<Map<String,Object>> queryMapList(String sql,Object... args){
		MapListHandler rsh = new MapListHandler();
		List<Map<String,Object>> result = null;
		try{
			QueryRunner qryRun = new QueryRunner(DBHelper.getDataSource());
			result = qryRun.query(sql,rsh,args);
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		return result;
	}
	
	
	public static long executeUpdate(String sql,Object...args){
		long id=0;
		try{
			QueryRunner qryRun = new QueryRunner(DBHelper.getDataSource());
			id = qryRun.update(sql,args);
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		return id;
	}
	public static long insert(String sql,Object... args){
		return executeUpdate(sql,args);
	}

	public static long update(String sql,Object... args){
		return executeUpdate(sql,args);
	}
	public static void delete(String sql,Object... args){
		executeUpdate(sql,args);
	}
	
	public static int count(String sql,Object... args){
		int ret = 0;
		try{
			QueryRunner qryRun = new QueryRunner(DBHelper.getDataSource());		
		    Object obj = qryRun.query(sql, new ScalarHandler());
		    ret = Integer.parseInt(String.valueOf(obj));
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		return ret;
		    
	}

}
